package com.atguigu.ssyx.acl.utils;

import com.atguigu.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 根据权限数据构建菜单数据
 * Author Xu Chen xu
 * Create 2024/4/24 - 下午7:46
 * version v1.0
 */
public class PermissionHelper {

    public static List<Permission> buildPermission(List<Permission> treeNodes) {
        List<Permission> treeList = new ArrayList<>();

        for (Permission treeNode : treeNodes){
            if (treeNode.getPid() == 0){
                treeNode.setLevel(1);
                treeList.add(findChildren(treeNode,treeNodes));
            }
        }
        return treeList;
    }

    private static Permission findChildren(Permission treeNode, List<Permission> treeNodes) {
        treeNode.setChildren(new ArrayList<>());

        for (Permission it : treeNodes){
            if (treeNode.getId().longValue() == it.getPid().longValue()){
                int level = treeNode.getLevel() + 1;
                it.setLevel(level);
                if (treeNode.getChildren() == null){
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }
}
